package com.bdqn.controller;

import com.bdqn.pojo.User;
import com.bdqn.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * IndexController
 */
@Controller
public class IndexController {

    @Resource
    private UserService userService;

    @GetMapping("/login")
    public String toLogin() {
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(Model model, HttpSession session, String usrName, String usrPassword) {
        // 用户登录，成功返回当前用户信息
        User loginUser = userService.login(usrName, usrPassword);
        // 用户密码不匹配
        if (loginUser == null) {
            model.addAttribute("message", "账号或密码错误，请重新登录。");
            return "login";
        }
        // 把用户保存到Session中
        session.setAttribute("loginUser", loginUser);

        return "redirect:/main";
    }

    @GetMapping("/main")
    public String toMain() {
        return "main";
    }

    @GetMapping("/logout")
    public String doLogout(HttpSession session) {
        session.removeAttribute("loginUser");
        session.invalidate();
        return "redirect:/login";
    }
}
